from django.contrib.auth.base_user import AbstractBaseUser
from django.db import models
from django.contrib.auth.models import AbstractUser, UserManager
from apps.UserControl.models.base import BaseModel


class UsersManager(models.Manager):

    def create_user(self, username, password, **extra_fields):
        if not username:
            raise ValueError('The given username must be set')
        # username if isinstance(username, str) else raise ValueError('格式')
        if isinstance(username, str):
            user = User(username=username, **extra_fields)
            user.set_password(password)
            user.save()
            return user
        else:
            raise ValueError("格式错误！")

    def get_by_natural_key(self, username):
        return self.get(**{self.model.USERNAME_FIELD: username})


class User(BaseModel, AbstractBaseUser):
    username = models.CharField(max_length=32, unique=True)
    USERNAME_FIELD = 'username'

    # upload_to = 'imgs'
    portrait = models.ImageField(verbose_name='头像', upload_to='portrait')
    email = models.EmailField(verbose_name='email address', blank=False)
    phone = models.CharField(null=False, blank=False, max_length=11, unique=False, verbose_name="联系电话")
    name = models.CharField(null=True, blank=True, max_length=32, unique=False, verbose_name="姓名")
    sex_choice = (
        ('man', '男'),
        ('girl', '女')
    )
    position = models.CharField(null=True, blank=True, max_length=20, verbose_name='职位')
    sex = models.CharField(null=False, blank=False, choices=sex_choice, default='max', max_length=6, verbose_name='性别')
    is_system = models.BooleanField(null=False, blank=False, default=False, verbose_name='是否内置')
    permission = models.ManyToManyField(blank=True, to='Permissions', related_name='user', verbose_name='权限')
    is_superuser = models.BooleanField(verbose_name='超级管理员', default=False)
    is_active = models.BooleanField(null=False, blank=False, default='1', verbose_name='是否激活')
    # REQUIRED_FIELDS = ['username', 'password']
    # objects = UserManager()
    objects = UsersManager()

    class Meta:
        verbose_name = '用户'
        verbose_name_plural = verbose_name
        db_table = 'control_user'
        ordering = ('username',)

    # def __str__(self):
    #     return self.username
